<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * Catalog product controller
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

require_once("Mage/Adminhtml/controllers/Catalog/ProductController.php");
class Silk_Zgb_Adminhtml_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
    /**
     * Initialize product from request parameters
     *
     * @return Mage_Catalog_Model_Product
     */
    protected function _initProduct()
    {
        $currentWebsiteId = Mage::helper("qslb")->_getwebsiteId();
        if($currentWebsiteId)
        {
            $storeId = Mage::getModel('core/website')->load($currentWebsiteId)->getDefaultStore()->getId();
        }
        else
        {
            $storeId = $this->getRequest()->getParam('store',0);
        }

        $this->_title($this->__('Catalog'))
             ->_title($this->__('Manage Products'));

        $productId  = (int) $this->getRequest()->getParam('id');
        $product    = Mage::getModel('catalog/product')
            ->setStoreId($storeId);

        if (!$productId) {
            if ($setId = (int) $this->getRequest()->getParam('set')) {
                $product->setAttributeSetId($setId);
            }

            if ($typeId = $this->getRequest()->getParam('type')) {
                $product->setTypeId($typeId);
            }
        }

        $product->setData('_edit_mode', true);
        if ($productId) {
            try {
                $product->load($productId);
            } catch (Exception $e) {
                $product->setTypeId(Mage_Catalog_Model_Product_Type::DEFAULT_TYPE);
                Mage::logException($e);
            }
        }

        $attributes = $this->getRequest()->getParam('attributes');
        if ($attributes && $product->isConfigurable() &&
            (!$productId || !$product->getTypeInstance()->getUsedProductAttributeIds())) {
            $product->getTypeInstance()->setUsedProductAttributeIds(
                explode(",", base64_decode(urldecode($attributes)))
            );
        }

        // Required attributes of simple product for configurable creation
        if ($this->getRequest()->getParam('popup')
            && $requiredAttributes = $this->getRequest()->getParam('required')) {
            $requiredAttributes = explode(",", $requiredAttributes);
            foreach ($product->getAttributes() as $attribute) {
                if (in_array($attribute->getId(), $requiredAttributes)) {
                    $attribute->setIsRequired(1);
                }
            }
        }

        if ($this->getRequest()->getParam('popup')
            && $this->getRequest()->getParam('product')
            && !is_array($this->getRequest()->getParam('product'))
            && $this->getRequest()->getParam('id', false) === false) {

            $configProduct = Mage::getModel('catalog/product')
                ->setStoreId(0)
                ->load($this->getRequest()->getParam('product'))
                ->setTypeId($this->getRequest()->getParam('type'));

            /* @var $configProduct Mage_Catalog_Model_Product */
            $data = array();
            foreach ($configProduct->getTypeInstance()->getEditableAttributes() as $attribute) {

                /* @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
                if(!$attribute->getIsUnique()
                    && $attribute->getFrontend()->getInputType()!='gallery'
                    && $attribute->getAttributeCode() != 'required_options'
                    && $attribute->getAttributeCode() != 'has_options'
                    && $attribute->getAttributeCode() != $configProduct->getIdFieldName()) {
                    $data[$attribute->getAttributeCode()] = $configProduct->getData($attribute->getAttributeCode());
                }
            }

            $product->addData($data)
                ->setWebsiteIds($configProduct->getWebsiteIds());
        }

        Mage::register('product', $product);
        Mage::register('current_product', $product);
        Mage::getSingleton('cms/wysiwyg_config')->setStoreId($this->getRequest()->getParam('store'));
        return $product;
    }


    /**
     * Save product action
     */
    public function saveAction()
    {
        $currentWebsiteId = Mage::helper("qslb")->_getwebsiteId();

        if($currentWebsiteId)
        {
            $storeId = Mage::getModel('core/website')->load($currentWebsiteId)->getDefaultStore()->getId();

        }
        else
        {
            $storeId = $this->getRequest()->getParam('store',0);
        }

        $redirectBack   = $this->getRequest()->getParam('back', false);
        $productId      = $this->getRequest()->getParam('id');
        $isEdit         = (int)($this->getRequest()->getParam('id') != null);

        $data = $this->getRequest()->getPost();
        
        if ($data) {
        	$this->_filterStockData($data['product']['stock_data']);
        	$product = $this->_initProductSave();
        	try {
        		$product->save();
        		$productId 	= $product->getId();
        		$product 	= Mage::getModel("catalog/product")->load($productId);
        		if (isset($data['copy_to_stores'])) {
        			$this->_copyAttributesBetweenStores($data['copy_to_stores'], $product);
        		}
        	} catch (Mage_Core_Exception $e) {
        		$this->_getSession()->addError($e->getMessage())
        		->setProductData($data);
        		$redirectBack = true;
        	} catch (Exception $e) {
        		Mage::logException($e);
        		$this->_getSession()->addError($e->getMessage());
        		$redirectBack = true;
        	}
        	Mage::helper('zgb')->reindexCategoryProduct($storeId, $product, $data);
        }
        //exit(0);
        if ($redirectBack) {
            $this->_redirect('*/*/edit', array(
                'id'    => $productId,
                '_current'=>true
            ));
        } elseif($this->getRequest()->getParam('popup')) {
            $this->_redirect('*/*/created', array(
                '_current'   => true,
                'id'         => $productId,
                'edit'       => $isEdit
            ));
        } else {
        	$this->_getSession()->addSuccess("添加商品成功");
        	$this->_redirect('*/*/', array('store'=>$storeId)); 
        }
    }
    
    protected function _initProductSave()
    {
        $product     = $this->_initProduct();
        $productData = $this->getRequest()->getPost('product');
        unset($productData["special_price"]);
        unset($productData["special_from_date"]);
        unset($productData["special_to_date"]);
        if ($productData) {
            $this->_filterStockData($productData['stock_data']);
        }

        /**
         * Websites
         */
        if (!isset($productData['website_ids'])) {
            $productData['website_ids'] = array();
        }

        $wasLockedMedia = false;
        if ($product->isLockedAttribute('media')) {
            $product->unlockAttribute('media');
            $wasLockedMedia = true;
        }

        $product->addData($productData);

        if ($wasLockedMedia) {
            $product->lockAttribute('media');
        }

        if (Mage::app()->isSingleStoreMode()) {
            $product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));
        }

        /**
         * Create Permanent Redirect for old URL key
         */
        if ($product->getId() && isset($productData['url_key_create_redirect']))
        // && $product->getOrigData('url_key') != $product->getData('url_key')
        {
            $product->setData('save_rewrites_history', (bool)$productData['url_key_create_redirect']);
        }

        /**
         * Check "Use Default Value" checkboxes values
         */
        if ($useDefaults = $this->getRequest()->getPost('use_default')) {
            foreach ($useDefaults as $attributeCode) {
                $product->setData($attributeCode, false);
            }
        }

        /**
         * Init product links data (related, upsell, crosssel)
         */
        $links = $this->getRequest()->getPost('links');
        if (isset($links['related']) && !$product->getRelatedReadonly()) {
            $product->setRelatedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['related']));
        }
        if (isset($links['upsell']) && !$product->getUpsellReadonly()) {
            $product->setUpSellLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['upsell']));
        }
        if (isset($links['crosssell']) && !$product->getCrosssellReadonly()) {
            $product->setCrossSellLinkData(Mage::helper('adminhtml/js')
                ->decodeGridSerializedInput($links['crosssell']));
        }
        if (isset($links['grouped']) && !$product->getGroupedReadonly()) {
            $product->setGroupedLinkData(Mage::helper('adminhtml/js')->decodeGridSerializedInput($links['grouped']));
        }

        /**
         * Initialize product categories
         */
        $categoryIds = $this->getRequest()->getPost('category_ids');
        if (null !== $categoryIds) {
            if (empty($categoryIds)) {
                $categoryIds = array();
            }
            $product->setCategoryIds($categoryIds);
        }

        /**
         * Initialize data for configurable product
         */
        if (($data = $this->getRequest()->getPost('configurable_products_data'))
            && !$product->getConfigurableReadonly()
        ) {
            $product->setConfigurableProductsData(Mage::helper('core')->jsonDecode($data));
        }
        if (($data = $this->getRequest()->getPost('configurable_attributes_data'))
            && !$product->getConfigurableReadonly()
        ) {
            $product->setConfigurableAttributesData(Mage::helper('core')->jsonDecode($data));
        }

        $product->setCanSaveConfigurableAttributes(
            (bool) $this->getRequest()->getPost('affect_configurable_product_attributes')
                && !$product->getConfigurableReadonly()
        );

        /**
         * Initialize product options
         */
        if (isset($productData['options']) && !$product->getOptionsReadonly()) {
            $product->setProductOptions($productData['options']);
        }

        $product->setCanSaveCustomOptions(
            (bool)$this->getRequest()->getPost('affect_product_custom_options')
            && !$product->getOptionsReadonly()
        );

        Mage::dispatchEvent(
            'catalog_product_prepare_save',
            array('product' => $product, 'request' => $this->getRequest())
        );

        return $product;
    }
    
    //站点分配 
     public function addwebsiteAction(){
         $productIds = $this->getRequest()->getParam('product');
         $websiteId = Mage::getSingleton('admin/session')->getUser()->getWebsiteId();
         if(!$websiteId)
         {
             $websiteId = $this->getRequest()->getParam('toWebsiteId');
         }
         
         $storeId = Mage::getModel('core/website')->load($websiteId)->getDefaultStore()->getId();
         if (!is_array($productIds)) {
             $this->_getSession()->addError($this->__('Please select product(s).'));
         } else {
             if (!empty($productIds)) {
                 //判断当前商品是否已分配站点
                 $productName = null;
                 $inId=array();
                 foreach ($productIds as $productId) {
                     $product = Mage::getModel("catalog/product")->load($productId);
                     $websiteIds = $product->getWebsiteIds();
                     if(in_array($websiteId, $websiteIds)){
                         $productName.=$product->getName().",";
                         $inId[] = $productId;
                     }
                 }
                 //去掉已分配商品Id
                $productIds=array_diff($productIds,$inId);

                //判断是否还有商品
                if(!count($productIds)){
                     $this->_getSession()->addError($this->__($productName."这些商品已经存在于该站点,请重新选择要分配的商品"));
                     $this->_redirect('adminhtml/catalog_product/index');
                     return;
                }
                 try {
                    foreach ($productIds as $productId) {
                         $product = Mage::getModel("catalog/product")->load($productId);
                         $websiteIds = $product->getWebsiteIds();
                         $websiteIds[] = $websiteId;
                         $product->setWebsiteIds($websiteIds);
                         $product->save();
                         $product = Mage::getModel("catalog/product")->setStoreId($storeId)->load($productId);
                         $product->setStatus(2);
                         $product->setSpecialPrice(null);
                         $product->setSpecialFromDate(null);
                         $product->setSpecialToDate(null);

                         //判断aitoc_cataloginventory_stock_item是否存在记录
                         $resource = Mage::getSingleton('core/resource');
                         $db = $resource->getConnection('core_read');
                         $sql = "select * from aitoc_cataloginventory_stock_item where product_id='{$productId}' and website_id='{$websiteId}'";
                         $result = $db->fetchAll($sql);

                         if($result){
                            $sql = "update aitoc_cataloginventory_stock_item set qty= 0 where product_id='{$productId}' and website_id='{$websiteId}' and stock_id=1";
                            $db->exec($sql);    
                         }else{
                            //
                            try
                            {
                            	if($websiteId == '11')
                            	{
                            		$stockItemq = Mage::getModel('cataloginventory/stock_item');
                            		$stockItemq->setProductId($productId);
                            		$stockItemq->setWebsiteId($websiteId);
                            		$stockItemq->setStockId(1);
                            		$stockItemq->setQty(0);
                            		$stockItemq->save();
                            	}
                            	else
                            	{
                            		$product->getStockItem()->setQty(0)->save();
                            		$product->save();
                            	}
                            }
                            catch(Exception $e)
                            {
                                Mage::logException($e);
                            }
                         }
                     }
                     if($productName){
                         $this->_getSession()->addSuccess(
                            $this->__($productName."商品已经存在于该站点，其他商品分配站点成功"));
                     }else{
                        $this->_getSession()->addSuccess(
                           $this->__("商品分配站点成功")
                        ); 
                     }
                     
                 } catch (Exception $e) {
                     $this->_getSession()->addError($e->getMessage());
                 }
             }
         }
         $this->_redirect('adminhtml/catalog_product/index');
     }
}
